package 链表与双指针.m03.d06.t01;

import 链表与双指针.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, cur = null;
        int up = 0;
        while(l1 != null || l2 != null) {
            // System.out.println("======");
            int lval1 = (l1 == null) ? 0 : l1.val;
            int lval2 = (l2 == null) ? 0 : l2.val;
            int res = lval1 + lval2 + up;
            up = res / 10;
            int remainder = res % 10;
            if (head == null) {
                head = new ListNode(remainder, null);
                cur = head;
            } else {
                ListNode node = new ListNode(remainder, null);
                cur.next = node;
                cur = node;
            }
            if(l1 != null) {
                l1 = l1.next;
            }
            if(l2 != null) {
                l2 = l2.next;
            }
        }
        if(l1 == null && l2 == null && up == 1) {
            cur.next = new ListNode(1, null);
        }
        return head;
    }
}